package com.hanamaki.jdbc.until;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

/**
 * @author hanamaki
 * @version 1.0
 * @date 2021/7/1 13:39
 */
// 如果 工具类  类中的方法尽量使用静态方法
public class JDBC_Util {
    static String url;
    static String driver;
    static String username;
    static String password;

    static{
//        首先获取 db.properties 配置文件中的信息
        Properties properties = new Properties();
//        绝对路径
        try {
//            properties.load(new FileInputStream("D:\\SoftWareInstall\\JavaSpace\\IdeaSpace\\javastudy-618\\src\\com\\hanamaki\\jdbc\\until\\info\\db.properties"));
//            相对路径
            properties.load(new FileInputStream("src/com/hanamaki/jdbc/until/info/db.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        url = properties.getProperty("url");
        driver = properties.getProperty("driver");
        username = properties.getProperty("username");
        password = properties.getProperty("password");

//        加载数据库的驱动
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    //     方法
    public static Connection getCon(){
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url, username, password);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return connection;
    }

    public static void refresh(Connection connection, Statement statement, ResultSet resultSet, PreparedStatement preparedStatement) {
        try {
            if (connection != null) {
                connection.close();
            }
            if (statement != null) {
                statement.close();
            }
            if (resultSet != null) {
                resultSet.close();
            }
            if (preparedStatement != null) {
                preparedStatement.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
